<template>
  <div class="bg-gray transfer" v-loading="transferLoading">
    <div class="title">{{$t('nav.transfer')}}</div>
    <div class="w1200 transfer_info">
      <el-form :model="transferForm" status-icon :rules="transferRules" ref="transferForm" class=" w630 transfer_form">
        <el-form-item :label="$t('transfer.transfer0')">
          <el-input v-model="transferForm.fromAddress" autocomplete="off" disabled>
          </el-input>
        </el-form-item>
        <!-- <div class="fr book"><i class="iconfont iconlianxiren click font16" slot="suffix" @click="showBook"></i></div> -->
        <el-form-item :label="$t('transfer.transfer1')" prop="toAddress">
          <el-input v-model="transferForm.toAddress" autocomplete="off">
          </el-input>
        </el-form-item>
        <el-form-item :label="$t('transfer.transfer2')" prop="assetType">
          <el-select v-model="transferForm.assetType" class="asset_type" @change="changeType">
            <!-- <el-option v-for="(item,index) in assetsList"
                       :key="index"
                       :label="item.symbol"
                       :value="item"
                       :disabled="toAddressInfo.transferType ===5 && item.type === 2">
            </el-option> -->
            <el-option v-for="(item,index) in assetsListnewAtr"
                       :key="index"
                       :label="item"
                       :value="item"
                       :disabled="toAddressInfo.transferType ===5 && item.type === 2">
            </el-option>
          </el-select>
        </el-form-item>
        <div class="font12 fr balance">{{$t('consensus.consensus2')}}：{{keyongBlance}}
          <!-- <span>{{assetsInfo.symbol}}</span></div> -->
          <span>ATR</span></div>
        <el-form-item :label="$t('transfer.transfer3')" prop="amount">
          <el-input v-model="transferForm.amount" autocomplete="off">
          </el-input>
        </el-form-item>
        <!-- <div class="fr click all" @click="allAvailable">{{$t('transfer.transfer24')}}</div> -->
        <!-- <el-switch v-show="assetsInfo.type !==1" v-model="seniorValue" :inactive-text="$t('call.call3')" width="35"
                   class="senior_value fr">
        </el-switch> -->
        <div v-show="seniorValue" class="senior_list cb">
          <el-form-item label="Gas Limit" prop="gas">
            <el-input v-model="transferForm.gas" autocomplete="off">
            </el-input>
          </el-form-item>
          <el-form-item label="Price" prop="price">
            <el-input v-model="transferForm.price" autocomplete="off">
            </el-input>
          </el-form-item>
        </div>
        <!-- <el-form-item :label="$t('transfer.transfer4')" class="remarks">
          <el-input type="textarea" :rows="2" v-model="transferForm.remarks" maxlength="200" show-word-limit>
          </el-input>
        </el-form-item> -->
        <!-- <div class="font14 mb_20">
          <el-tooltip placement="top">
            <div slot="content">{{$t('transfer.transfer5')}}</div>
            <i class="el-icon-warning"></i>
          </el-tooltip>
          {{$t('public.fee')}}: {{transferForm.fee}}
          <span class="fCN">{{defaultInfo.defaultAsset.symbol}}</span>
        </div> -->
        <el-form-item class="tc">
          <el-button type="success" @click="submitTransferForm('transferForm')">{{$t('public.next')}}</el-button>
        </el-form-item>
      </el-form>
    </div>

    <el-dialog :title="$t('public.bookList')" width="50rem" class="book-dialog"
               :visible.sync="bookDialog"
               :close-on-click-modal="false"
               :close-on-press-escape="false">
      <el-table :data="bookData">
        <el-table-column property="name" :label="$t('transfer.transfer4')" width="100" align="center">
        </el-table-column>
        <el-table-column property="address" :label="$t('tab.tab11')" min-width="300" align="center">
        </el-table-column>
        <el-table-column property="alias" :label="$t('address.address3')" width="100" align="center">
        </el-table-column>
      </el-table>
    </el-dialog>

    <el-dialog :title="$t('transfer.transfer6')" width="46rem" class="confirm-dialog"
               :visible.sync="transferDiolog"
               :show-close="false"
               :close-on-click-modal="false"
               :close-on-press-escape="false">
      <div class="bg-white">
        <div class="div-data">
          <p>{{$t('transfer.transfer0')}}&nbsp;</p>
          <label>{{transferForm.fromAddress}}</label>
        </div>
        <div class="div-data">
          <p>{{$t('transfer.transfer1')}}&nbsp;</p>
          <label v-if="aliasToAddress">{{aliasToAddress}}({{transferForm.toAddress}})</label>
          <label v-else>{{transferForm.toAddress}}</label>
        </div>
        <!-- <div class="div-data">
          <p>{{$t('public.fee')}}&nbsp;</p>
          <label>{{transferForm.fee}} <span class="fCN">ATR</span></label>
        </div> -->
        <div class="div-data cb">
          <p>{{$t('tab.tab6')}}&nbsp;</p>
          <label class="yellow">{{transferForm.amount}} <span class="fCN">{{assetsInfo.symbol}}</span></label>
        </div>
      </div>
      <div slot="footer" class="dialog-footer cb">
        <el-button @click="transferDiolog = false">{{$t('transfer.transfer7')}}</el-button>
        <el-button type="success" @click="confirmTransfer">{{$t('transfer.transfer8')}}</el-button>
      </div>
    </el-dialog>

    <Password ref="password" @passwordSubmit="passSubmit">
    </Password>
  </div>
</template>

<script>
  // import tronWeb from 'tronweb'
  import nuls from 'nuls-sdk-js'
  import sdk from 'nuls-sdk-js/lib/api/sdk'
  import utils from 'nuls-sdk-js/lib/utils/utils'
  import {
    isMainNet,
    countCtxFee,
    getNulsBalance,
    inputsOrOutputs,
    validateAndBroadcast,
    commitData
  } from '@/api/requestData'
  import {MAIN_INFO} from '@/config.js'
  import {
    Times,
    Plus,
    Division,
    Minus,
    timesDecimals,
    timesDecimals0,
    timesDecimalsBig,
    addressInfo,
    passwordVerification,
    htmlEncode,
    getRamNumber,
    divisionDecimals
  } from '@/api/util'
  import Password from '@/components/PasswordBar'

  export default {

    data() {
      let validateToAddress = async (rule, value, callback) => {
        //根据长度验证地址或者别名验证
        let aliasRes = {};
        if (value.length > 30) {
          this.toAddressInfo = nuls.verifyAddress(value);
          if (this.toAddressInfo.type === 1) { //主链地址
            let verifyToAddress = await this.verifyToAddress();
            //console.log(verifyToAddress);
            if (!verifyToAddress) {
              callback(new Error(verifyToAddress.data))
            }
          }
        }

        if (value === '') {
          callback(new Error(this.$t('transfer.transfer9')))
        } else if (value.length < 20 && !aliasRes.success) {
          callback(new Error(this.$t('transfer.transfer23')))
        } else {
          if (this.transferForm.amount !== '') {
            this.$refs.transferForm.validateField('amount');
          }
          callback()
        }
      };
      let validateAmount = (rule, value, callback) => {
        let patrn = new RegExp("^([1-9][\\d]{0,20}|0)(\\.[\\d]{1," + this.assetsInfo.decimals + "})?$");
        this.available = Number(this.assetsInfo.balance);
        if (this.assetsInfo.type === 1 && this.assetsInfo.symbol === 'ATR') {
          this.available = Number(Minus(this.assetsInfo.balance, this.transferForm.fee))
        }
        if (value === '') {
          callback(new Error(this.$t('transfer.transfer11')))
        } else if (!patrn.exec(value)) {
          // callback(new Error(this.$t('transfer.transfer12') + ": " + this.assetsInfo.decimals))
          callback(new Error(this.$t('transfer.transfer12') + ": 3"))
        } else if (value < 0.001 && this.assetsInfo.symbol === 'ATR') {
          callback(new Error(this.$t('transfer.transfer13')))
        } else if (value > this.available) {
          callback(new Error(this.$t('transfer.transfer131') + ": " + this.available))
        } else {
          callback()
        }
      };
      let validateGas = (rule, value, callback) => {
        if (!value) {
          callback(new Error(this.$t('deploy.deploy8')));
        } else if (value < 1 || value > 10000000) {
          callback(new Error(this.$t('deploy.deploy81')));
        } else {
          callback();
        }
      };
      let validatePrice = (rule, value, callback) => {
        if (!value) {
          callback(new Error(this.$t('deploy.deploy9')));
        } else if (value < 1) {
          callback(new Error(this.$t('deploy.deploy91')));
        } else {
          callback();
        }
      };

      return {
        addressInfo: '', //默认账户信息
        defaultInfo: {},//默认链信息
        assetsList: '',//资产列表
        assetsInfo: {},//选中的资产信息
        balanceInfo: {},//balance信息
        available: 0,//可用余额
        contractInfo: {},//合约信息
        transferForm: {
          fromAddress: '',
          toAddress: '',
          assetType: 'ATR',
          amount: '',
          gas: 1,
          price: 25,
          remarks: '',
          fee: 0.001
        },
        transferRules: {
          toAddress: [{validator: validateToAddress, trigger: ['blur']}],
          amount: [{validator: validateAmount, trigger: ['blur', 'change']}],
          gas: [{validator: validateGas, trigger: ['blur', 'change']}],
          price: [{validator: validatePrice, trigger: ['blur', 'change']}],
        },
        seniorValue: false,//高级选项
        toAddressInfo: {},//收款地址信息（transferType 1:NULS转账 2：token转账 3：向合约转NULS 4：向合约转token 5：跨链交易）
        aliasToAddress: '',//别名地址
        contractCallData: {},//合约信息
        gasInfo: {number: 0, oldNumber: 0},//gas信息
        contractFee: 0,//调用合约手续费
        bookDialog: false,//通讯录弹框
        bookData: [],//通讯录数据
        transferDiolog: false,//确认弹框
        transferLoading: false,//加载动画
        keyongBlance: 0,

        tronwebApi: 'http://47.108.136.230:9991',
      };
    },
    created() {
      // sessionStorage.setItem('assetsList', JSON.stringify({newList}));
      this.assetsListnewAtr = ['ATR']
      this.addressInfo = addressInfo(1);
      this.transferForm.fromAddress = this.addressInfo.address;
      this.defaultInfo = JSON.parse(sessionStorage.getItem('info'))
    },
    mounted() {
      // this.getCapitalListByAddress(this.addressInfo.address);
      setInterval(() => {
        this.addressInfo = addressInfo(1);
      }, 500);
      this.getAddressInfoByNode(this.addressInfo)
      // console.log(this.assetsInfo.balance);
    },
    watch: {
      addressInfo(val, old) {
        if (val.address !== old.address && old.address) {
          this.transferForm.fromAddress = this.addressInfo.address;
          // this.getCapitalListByAddress(this.addressInfo.address);
          if (this.transferForm.toAddress) {
            this.$refs.transferForm.validateField('toAddress');
          }
        }
      },
    },
    components: {
      Password,
    },
    methods: {

      /**
       * 资产类型选择
       * @param type
       **/
      async changeType(type) {
        //console.log(type);
        this.assetsInfo = type;
        // this.transferForm.assetType = type.symbol;
        this.transferForm.assetType = type;
        if (this.transferForm.amount !== '') {
          this.$refs.transferForm.validateField('amount');
        }
      },

      /**
       * 下一步
       * @params: formName
       * @date: 2020-06-29 20:17
       * @author: Wave
       */
      submitTransferForm(formName) {
        this.$refs[formName].validate((valid) => {
          if (valid) {
            if (this.toAddressInfo.transferType === 2) {
              this.transferForm.fee = this.contractFee;
            }
            this.transferDiolog = true;

          } else {
            return false;
          }
        });
      },

      /**
       * @disc: 确认提交
       * @params:
       * @date: 2020-06-30 14:35
       * @author: Wave
       */
      async confirmTransfer() {
        if (this.addressInfo.aesPri) {
          this.$refs.password.showPassword(true);
        } else {

          console.log('进入确认提交')

          this.balanceInfo = await this.getNulsBalance(this.assetsInfo.chainId, 1, this.transferForm.fromAddress);
          //console.log(this.toAddressInfo);
          if (this.toAddressInfo.transferType !== 1) {
            this.$message({message: this.$t('tips.tips2'), type: 'warning', duration: 3000});
            return;
          }
          let txHexKey = await getRamNumber(16);
          let signDataKey = await getRamNumber(16);
          let assembleHex = await this.transferAssemble();
          //console.log(assembleHex);
          if (!assembleHex.success) {
            this.$message({message: this.$t('tips.tips3'), type: 'error', duration: 3000});
            return;
          }
          let commitDatas = await commitData(txHexKey, signDataKey, this.addressInfo.address, assembleHex.data);
          //console.log(commitDatas);
          if (!commitDatas.success) {
            this.$message({
              message: this.$t('tips.tips4') + JSON.stringify(commitDatas.data),
              type: 'error',
              duration: 3000
            });
            return;
          }
          this.$refs.password.showScan(commitDatas.data.txInfo, commitDatas.data.assembleHex);
        }

      },

      /**
       *  获取密码框的密码
       * @param password
       **/
      async passSubmit(password) {
        let passwordInfo = await passwordVerification(this.addressInfo, this.$md5(password));
        if (!passwordInfo.success) {
          this.$message({message: this.$t('address.address13'), type: 'error', duration: 3000});
          return;
        }

        this.transferDiolog = false;
        this.transferLoading = true;

        let transferInfo = {
          fromAddress: this.transferForm.fromAddress,
          toAddress: this.aliasToAddress ? this.aliasToAddress : this.transferForm.toAddress,
          assetType: this.transferForm.assetType,
          amount: this.transferForm.amount,
          gas: this.transferForm.gas,
          price: this.transferForm.price,
          remarks: this.transferForm.remarks,
          fee: Number(timesDecimals0(this.transferForm.fee, this.defaultInfo.defaultAsset.decimals)),
          assetsChainId: this.assetsInfo.chainId,
          assetsId: this.assetsInfo.assetId,
        };
        // console.log(transferInfo);
        // console.log('this.addressInfo',this.addressInfo);
        let isPassword = await passwordVerification(this.addressInfo, this.$md5(password), this.prefix);
        // console.log('isPassword',isPassword);


        const TronWeb = require('tronweb')
        const tronWeb = new TronWeb({
            fullHost: this.tronwebApi,
            privateKey: ''
        })
        tronWeb.trx.sendTransaction(transferInfo.toAddress, transferInfo.amount*1000000,isPassword.pri)

        this.toUrl("txList");
        this.transferLoading = false;
      },

      /**
       * 连接跳转
       * @param name
       */
      toUrl(name) {
        //console.log(name)
        this.$router.push({
          name: name
        })
      },

      /**
       * 获取地址网络信息
       * @param addressInfo
       **/
      async getAddressInfoByNode(addressInfo) {
        var paramsad = {
            address: addressInfo.address,
            visible: true
        }
        await this.$post('/wallet/getaccount', 'getAccount', paramsad)
          .then((response) => {
            // console.log('LLL',response)
            if (response.balance) {
              this.keyongBlance = response.balance / 1000000;
            }
          })
          .catch((error) => {
            console.log("getAccount:" + error);
          });
      },
    }
  }
</script>

<style lang="less">
  @import "./../../assets/css/style";

  .transfer {
    .title {
      line-height: 80px;
      height: 100px;
    }
    .transfer_info {
      min-height: 600px;
      border: 1px solid #c1c1c1;
      background-color: #ffffff;
      margin: -20px auto 0;
      .transfer_form {
        margin: 40px auto 0;
        .el-form-item {
          margin: 0 0 20px 0;
          .el-form-item__label {
            line-height: 20px;
          }
          .el-form-item__content {
            line-height: 30px;
            .el-input {
              .el-input__suffix {
                .el-input__icon {
                  line-height: 30px;
                }
              }
            }

            .el-form-item__error {
              font-size: 10px;
              padding: 1px 0 0 0;
            }
            .asset_type {
              width: 630px;
              .el-input {
                .el-input__inner {
                  width: 100%;
                }
              }
            }
            .el-button--success {
              width: 300px;
            }
          }
        }
        .book {
          width: 20px;
          height: 20px;
          z-index: 88;
          margin: 23px -23px 0 0;
        }
        .remarks {
          .el-form-item__label {
            line-height: 18px;
          }
        }
        .balance {
          margin: 5px 0 0 0;
        }
        .all {
          margin: -45px -26px 0 0;
          line-height: 20px;
          z-index: 88;
          position: relative;
          font-size: 10px;
        }
        .senior_value {
          height: 20px;
          margin: -10px 0 0 0;
          .el-switch__label {
            font-size: 12px;
          }
          .el-switch__core {
            width: 30px;
            height: 18px;
            &:after {
              height: 14px;
            }
          }
        }
      }
    }

    .confirm-dialog {
      .remark {
        label {
          display: block;
          width: 490px !important;
          float: right;
          height: 40px;
          overflow-y: auto;
          line-height: 20px;
          font-size: 12px;
        }
      }
    }
  }

</style>
